package com.project.basis.base;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.project.basis.utils.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseRecyclerViewAdapter.BaseRecyclerViewHolder> {

    protected OnItemClickListener<T> onItemClickListener;
    protected List<T> list;

    public BaseRecyclerViewAdapter() {
        list = new ArrayList<>();
    }

    @Override
    public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getItemViewId(viewType), parent, false);
        return new BaseRecyclerViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseRecyclerViewHolder holder, int i) {
        onBindViewDataHolder(holder, getItemData(holder.getAdapterPosition()), holder.getAdapterPosition());
    }

    protected abstract int getItemViewId(int viewType);

    protected abstract void onBindViewDataHolder(BaseRecyclerViewHolder holder, T data, int i);

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void setOnItemClickListener(OnItemClickListener<T> onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public void setList(List<T> list) {
        this.list.clear();
        this.list.addAll(list);
        notifyDataSetChanged();
    }

    public void addList(List<T> list) {
        this.list.addAll(list);
        notifyItemRangeInserted(this.list.size() - list.size(), list.size());
    }

    public void clearList() {
        list.clear();
        notifyDataSetChanged();
    }

    public List<T> getList() {
        return list;
    }

    public T getItemData(int position) {
        if (list.size() > position) {
            return list.get(position);
        }
        return null;
    }

    public static class BaseRecyclerViewHolder extends BaseViewHolder {

        public BaseRecyclerViewHolder(View itemView) {
            super(itemView);
        }
    }
}
